from django.http import JsonResponse
from django.views import View
from rest_framework.views import APIView
from rest_framework.views import Response
from myapp.models import *
from  .serializer import *
import json
# Create your views here.
class Login(APIView):
    def get(self, request):
        id= request.GET.get('id')
        print(id)
        user = User.objects.get(pk=id)
        user_ser = User_ser(user)
        return Response({'code': 200, 'data': user_ser.data})

    def post(self, request):
        name = request.POST.get('name')
        password = request.POST.get('password')
        print(name, password)
        user = User.objects.filter(name=name, password=password).first()
        if user:
            return Response({'code': 200, 'msg': '登录成功','name':user.name,'id':user.id})
        else:
            return Response({'code': 400, 'msg': '登录失败'})

class Show(APIView):
    def get(self,request):
        goods=Goods.objects.all()
        goods_ser= Goods_ser(goods,many=True)
        return Response({'code':200,'data':goods_ser.data})

class gift(APIView):
    def get(self,request):
        id= request.GET.get('id')
        print(id)
        user = User.objects.get(pk=id)
        user.is_gift = 0
        return Response({'code': 200, 'msg': '领取成功'})

class Pay(APIView):
    def get(self,request):
        id= request.GET.get('id')
        print(id)
        user = User.objects.get(pk=id)
        his=History.objects.filter(name=user.name).all()
        his_ser=History_ser(his,many=True)
        return Response({'code':200,'data':his_ser.data})

    def post(self,request):
        id= request.POST.get('id')
        # 获取价格
        price= int(request.POST.get('price'))
        cartstr= request.POST.get('cartstr')
        user = User.objects.get(pk=id)
        # 修改资金
        user.money=int(user.money)-price
        user.save()

        # 更改库存
        for i in eval(cartstr):
            good=Goods.objects.filter(name=i['name']).first()
            good.num = int(good.num) - int(i['num'])
            good.save()
        # 保存到记录表
        his=History(name=user.name,goods=cartstr,money=price)
        his.save()
        return Response({'code': 200, 'msg': '购买成功'})
